package com.zb.log;

import com.zb.utils.LoginLogUtil;
import com.zb.utils.BrowserUtil;
import com.zb.utils.RequestUtil;
import com.zb.vo.LoginVo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 登录日志
 * @Author WEN
 * @Date 2023/7/21 0021
 **/
@Aspect
@Component
public class PCLoginLogAspect {

    @Pointcut("execution(public * com.zb.system.controller.LoginController.login(..))")
    public static void PCLoginLogAspect(){}


    @AfterReturning("PCLoginLogAspect()")
    public void afterReturning(JoinPoint joinPoint) {
        HttpServletRequest request = RequestUtil.getRequestByContext();
        LoginVo loginVo = (LoginVo) joinPoint.getArgs()[0];
        LoginLogUtil.pcLoginSuccess(
                loginVo.getPhone(),
                BrowserUtil.getBrowser(request),
                Objects.equals(1, loginVo.getType())? "短信验证码登录" : "账号密码登录",
                BrowserUtil.getIpAddress(request));
    }

    @AfterThrowing(pointcut = "PCLoginLogAspect()",  throwing = "throwable")
    public void AfterThrowing(JoinPoint joinPoint, Throwable throwable) {
        HttpServletRequest request = RequestUtil.getRequestByContext();
        LoginVo loginVo = (LoginVo) joinPoint.getArgs()[0];
        LoginLogUtil.pcLoginError(
                loginVo.getPhone(),
                BrowserUtil.getBrowser(request),
                Objects.equals(1, loginVo.getType())? "短信验证码登录" : "账号密码登录",
                BrowserUtil.getIpAddress(request),
                throwable.getMessage()
                );
    }
}
